//
//  SmallDecisionsFxqViewController.h
//  SmallDecisions
//
//  Created by 李付雄 on 2025/08/28.
//

#import "SmallDecisionsFxqViewController.h"
#import "SmallDecisionsFxqButton.h"
#import "SmallDecisionsFxqViewController+Event.h"
#import "SmallDecisionsAlertViewController.h"
#import "SmallDecisionsFxqResultViewController.h"

#define FxqBtnSize 42
#define FxqBtnTopMargin (kScreenHeight - FxqBtnSize * 12 - 100 - NavBarHeight - SafeHeight) / 2.0

typedef enum : NSUInteger {
    SmallDecisionsFxqPeopleRoleTypeMan,
    SmallDecisionsFxqPeopleTypeWomen
} SmallDecisionsFxqPeopleRoleType;

@interface SmallDecisionsFxqViewController ()

@property (nonatomic, strong) UIImageView *fxqManImageView;
@property (nonatomic, strong) UIImageView *fxqWomenImageView;
@property (nonatomic, strong) UIImageView *fxqSzImageView;
@property (nonatomic, assign) BOOL fxqIsStart;
@property (nonatomic, strong) NSArray *fxqSzImags;
@property (nonatomic, assign) SmallDecisionsFxqPeopleRoleType currentFxqProplrRoleType;
@property (nonatomic, assign) int fxqManStepTotal;
@property (nonatomic, assign) int fxqWomenStepTotal;

@property (nonatomic, assign) int fxqRandom;


@end

@implementation SmallDecisionsFxqViewController

- (NSArray *)fxqSzImags {
    if(!_fxqSzImags) {
        _fxqSzImags = @[
            @"samll_deci_fxq_sz_one_icon",
            @"samll_deci_fxq_sz_two_icon",
            @"samll_deci_fxq_sz_three_icon",
            @"samll_deci_fxq_sz_four_icon",
            @"samll_deci_fxq_sz_five_icon",
            @"samll_deci_fxq_sz_six_icon",
        ];
    }
    return _fxqSzImags;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        self.currentFxqProplrRoleType = SmallDecisionsFxqPeopleRoleTypeMan;
        self.fxqTaskType = SmallDecisionsFxqTaskBaseType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self createSmallDecisionsFxqButtonUIPath];
    [self createSmallDecisionsFxqUserView];
    [self createSmallDecisionsFxqRuleView];
    [self loadSmallDecisionsFxqGame];
}

- (void)createSmallDecisionsFxqButtonUIPath {

    UIView *fxqLastBtn;

    NSArray <UIImage *> *fxqBtnImages = @[[UIImage imageNamed:@"samll_deci_fxq_item_red_high_bg"], [UIImage imageNamed:@"samll_deci_fxq_item_blue_high_bg"], [UIImage imageNamed:@"samll_deci_fxq_item_yellow_high_bg"], [UIImage imageNamed:@"samll_deci_fxq_item_green_high_bg"]];
    for (int i = 1; i <= 48; i ++) {
        SmallDecisionsFxqButton *fxqBtn = [SmallDecisionsFxqButton buttonWithType:UIButtonTypeCustom];
        fxqBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(18);
        [fxqBtn setBackgroundImage:fxqBtnImages[i % fxqBtnImages.count] forState:UIControlStateHighlighted];
        fxqBtn.tag = i;
        [self.view addSubview:fxqBtn];

        UITapGestureRecognizer *fxqBtnTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fxqAlertTaskMessageAction:)];
        [fxqBtn addGestureRecognizer:fxqBtnTapGes];

        if (i < 7) {
            if (!fxqLastBtn) {
                [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(FxqBtnTopMargin);
                    make.right.mas_equalTo(-(kScreenWidth - FxqBtnSize * 7 - 2 * 6) / 2 - FxqBtnSize - 2);
                    make.width.height.mas_equalTo(FxqBtnSize);
                }];
            } else {
                [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(fxqLastBtn.mas_top);
                    make.right.mas_equalTo(fxqLastBtn.mas_left).mas_offset(-2);
                    make.width.height.mas_equalTo(FxqBtnSize);
                }];
            }
        } else if (i < 18) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(fxqLastBtn.mas_bottom).mas_offset(2);
                make.left.mas_equalTo(fxqLastBtn.mas_left);
                make.width.height.mas_equalTo(FxqBtnSize);
            }];
        } else if (i < 20) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(fxqLastBtn.mas_top);
                make.left.mas_equalTo(fxqLastBtn.mas_right).mas_offset(2);
                make.width.height.mas_equalTo(FxqBtnSize);
            }];
        } else if (i < 26) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(fxqLastBtn.mas_top).mas_offset(-2);
                make.right.mas_equalTo(fxqLastBtn.mas_right);
                make.width.height.mas_equalTo(FxqBtnSize);
            }];
        } else if (i < 28) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(fxqLastBtn.mas_top);
                make.left.mas_equalTo(fxqLastBtn.mas_right).mas_offset(2);
                make.width.height.mas_equalTo(FxqBtnSize);
            }];
        } else if (i < 34) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(fxqLastBtn.mas_bottom).mas_offset(2);
                make.left.mas_equalTo(fxqLastBtn.mas_left);
                make.width.height.mas_equalTo(FxqBtnSize);
            }];
        } else if (i < 36) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(fxqLastBtn.mas_top);
                make.left.mas_equalTo(fxqLastBtn.mas_right).mas_offset(2);
                make.width.height.mas_equalTo(FxqBtnSize);
            }];
        } else if (i < 44) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(fxqLastBtn.mas_top).mas_offset(-2);
                make.left.mas_equalTo(fxqLastBtn.mas_left);
                make.width.height.mas_equalTo(FxqBtnSize);
            }];
        } else if (i < 47) {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(fxqLastBtn.mas_left).mas_offset(-2);
                make.width.height.mas_equalTo(FxqBtnSize);
                make.top.mas_equalTo(fxqLastBtn.mas_top);
            }];
        } else {
            [fxqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(fxqLastBtn.mas_left);
                make.width.height.mas_equalTo(FxqBtnSize);
                make.bottom.mas_equalTo(fxqLastBtn.mas_top).mas_offset(-2);
            }];
        }

        if(i == 48) {
            [fxqBtn setBackgroundImage:[UIImage imageNamed:@"samll_deci_fxq_item_end_icon"] forState:UIControlStateNormal];
        } else {
            [fxqBtn setTitle:[NSString stringWithFormat:@"%d", i] forState:UIControlStateNormal];
            [fxqBtn setBackgroundImage:fxqBtnImages[i % fxqBtnImages.count] forState:UIControlStateNormal];
            [fxqBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }

        fxqLastBtn = fxqBtn;
    }
}

- (void)createSmallDecisionsFxqUserView {
    UIImageView *beginImageView = [[UIImageView alloc] init];
    beginImageView.image = [UIImage imageNamed:@"samll_deci_fxq_item_start_icon"];
    [self.view addSubview:beginImageView];
    [beginImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo((kScreenWidth - FxqBtnSize * 6 - 2 * 5) / 2 + (FxqBtnSize * 6 - 2 * 5));
        make.width.height.mas_equalTo(FxqBtnSize);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(FxqBtnTopMargin);
    }];
    UIImageView *fxqManImageView = [[UIImageView alloc] init];
    fxqManImageView.image = [UIImage imageNamed:@"samll_deci_fxq_man_icon"];
    [self.view addSubview:fxqManImageView];
    self.fxqManImageView = fxqManImageView;

    UIImageView *fxqWomenImageView = [[UIImageView alloc] init];
    fxqWomenImageView.image = [UIImage imageNamed:@"samll_deci_fxq_women_icon"];
    [self.view addSubview:fxqWomenImageView];
    self.fxqWomenImageView = fxqWomenImageView;
}

- (void)createSmallDecisionsFxqRuleView {
    UIImageView *fxqHightImageView = [[UIImageView alloc] init];
    fxqHightImageView.animationImages = @[[UIImage imageNamed:@"samll_deci_fxq_dice_hight_one_icon"], [UIImage imageNamed:@"samll_deci_fxq_dice_hight_two_icon"], [UIImage imageNamed:@"samll_deci_fxq_dice_hight_three_icon"], [UIImage imageNamed:@"samll_deci_fxq_dice_hight_four_icon"]];
    fxqHightImageView.userInteractionEnabled = YES;
    [self.view addSubview:fxqHightImageView];
    [fxqHightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-10);
        make.centerX.mas_equalTo(self.view);
        make.width.height.mas_equalTo(80);
    }];
    self.fxqSzImageView = fxqHightImageView;

    UITapGestureRecognizer *diceTapGes = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [self beginSmallDecisionsFxqGame];
    }];
    [fxqHightImageView addGestureRecognizer:diceTapGes];

    UIButton *selectFxqTypeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [selectFxqTypeBtn setBackgroundImage:[UIImage imageNamed:@"samll_deci_fxq_bottom_change"] forState:UIControlStateNormal];
    [selectFxqTypeBtn setBackgroundImage:[UIImage imageNamed:@"samll_deci_fxq_bottom_change"] forState:UIControlStateHighlighted];
    [selectFxqTypeBtn addTarget:self action:@selector(selectSmallDecisionsFxqTypeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [selectFxqTypeBtn addTarget:self action:@selector(playSmallDecisionsFxqSystemSoundAction) forControlEvents:UIControlEventTouchDown];

    [self.view addSubview:selectFxqTypeBtn];
    [selectFxqTypeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(fxqHightImageView);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(65);
        make.width.mas_equalTo(72);
    }];

    UIButton *reloadFxqTaskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [reloadFxqTaskBtn setBackgroundImage:[UIImage imageNamed:@"samll_deci_fxq_bottom_refresh"] forState:UIControlStateNormal];
    [reloadFxqTaskBtn setBackgroundImage:[UIImage imageNamed:@"samll_deci_fxq_bottom_refresh"] forState:UIControlStateHighlighted];
    [reloadFxqTaskBtn addTarget:self action:@selector(reloadSmallDecisionsFxqTaskBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [reloadFxqTaskBtn addTarget:self action:@selector(playSmallDecisionsFxqSystemSoundAction) forControlEvents:UIControlEventTouchDown];

    [self.view addSubview:reloadFxqTaskBtn];
    [reloadFxqTaskBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(fxqHightImageView);
        make.left.mas_equalTo(30);
        make.height.mas_equalTo(65);
        make.width.mas_equalTo(72);
    }];
}

- (void)beginSmallDecisionsFxqGame {
    if (self.fxqIsStart) return;
    self.fxqIsStart = YES;

    CABasicAnimation *diceBasicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    diceBasicAnimation.fromValue = @(1.0);
    diceBasicAnimation.toValue = @(1.2);
    diceBasicAnimation.byValue = @(1.0);
    diceBasicAnimation.duration = 1;
    diceBasicAnimation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
    diceBasicAnimation.fillMode = kCAFillModeForwards;
    diceBasicAnimation.removedOnCompletion = YES;
    diceBasicAnimation.repeatCount = 1;
    [self.fxqSzImageView.layer addAnimation:diceBasicAnimation forKey:@"TransformScale"];

    [self.fxqSzImageView startAnimating];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.fxqRandom = arc4random() % 6;
        [self.fxqSzImageView stopAnimating];
        self.fxqSzImageView.image = [UIImage imageNamed:self.fxqSzImags[self.fxqRandom]];
        [self beginSmallDecisionsFxqAnimation];
    });
}

- (void)loadSmallDecisionsFxqGame {
    self.currentFxqProplrRoleType = self.currentFxqProplrRoleType == SmallDecisionsFxqPeopleTypeWomen ? SmallDecisionsFxqPeopleRoleTypeMan : SmallDecisionsFxqPeopleTypeWomen;
    self.fxqManStepTotal = 0;
    self.fxqWomenStepTotal = 0;

    self.fxqManImageView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - FxqBtnSize * 6 - 2 * 5) / 2 + (FxqBtnSize * 6 - 2 * 5), FxqBtnTopMargin - 25, FxqBtnSize, 50);
    self.fxqWomenImageView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - FxqBtnSize * 6 - 2 * 5) / 2 + (FxqBtnSize * 6 - 2 * 5), FxqBtnTopMargin - 25, FxqBtnSize, 50);
    self.fxqSzImageView.image = [UIImage imageNamed:self.fxqSzImags[5]];

    if (self.currentFxqProplrRoleType == SmallDecisionsFxqPeopleRoleTypeMan) {
        [self.view bringSubviewToFront:self.fxqManImageView];
    } else {
        [self.view bringSubviewToFront:self.fxqWomenImageView];
    }
}

- (void)beginSmallDecisionsFxqAnimation {
    NSInteger totalStepNum;
    switch (self.currentFxqProplrRoleType) {
        case SmallDecisionsFxqPeopleRoleTypeMan: {
            totalStepNum = self.fxqManStepTotal;
            self.fxqManStepTotal += self.fxqRandom + 1;
            if (self.fxqManStepTotal >= 48) {
                self.fxqManStepTotal = 48;
            }
            [self.view bringSubviewToFront:self.fxqManImageView];

        } break;
        case SmallDecisionsFxqPeopleTypeWomen: {
            totalStepNum = self.fxqWomenStepTotal;
            self.fxqWomenStepTotal += self.fxqRandom + 1;
            if (self.fxqWomenStepTotal >= 48) {
                self.fxqWomenStepTotal = 48;
            }
            [self.view bringSubviewToFront:self.fxqWomenImageView];
        } break;
        default:
            break;
    }
    [self autoSmallDecisionsFxqActionAnimation:totalStepNum + 1];
}

- (void)autoSmallDecisionsFxqActionAnimation:(NSInteger)tag {
    UIImageView *imageView;
    NSInteger totalStepNum;
    switch (self.currentFxqProplrRoleType) {
        case SmallDecisionsFxqPeopleRoleTypeMan: {
            imageView = self.fxqManImageView;
            totalStepNum = self.fxqManStepTotal;
        } break;
        case SmallDecisionsFxqPeopleTypeWomen: {
            imageView = self.fxqWomenImageView;
            totalStepNum = self.fxqWomenStepTotal;
        } break;
        default:
            break;
    }

    if (tag > totalStepNum) {
        if (self.currentFxqProplrRoleType == SmallDecisionsFxqPeopleRoleTypeMan) {
            self.currentFxqProplrRoleType = SmallDecisionsFxqPeopleTypeWomen;
        } else {
            self.currentFxqProplrRoleType = SmallDecisionsFxqPeopleRoleTypeMan;
        }
        self.fxqIsStart = NO;
        if (tag == 49) {
            [self showSmallDecisionsFxqResultWithTaskModel:nil viewTag:48];
        } else {
            NSUInteger index = tag - 2;
            if(index <= self.fxqTaskList.count ) {
                SmallDecisionsFxqTaskModel *model = self.fxqTaskList[index];
                [self showSmallDecisionsFxqResultWithTaskModel:model viewTag:index];
            }
        }
        return;
    }

    UIButton *btn = [self.view viewWithTag:tag];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [btn sendActionsForControlEvents:UIControlEventTouchDown];
    });
    [UIView animateWithDuration:0.35 animations:^{
        imageView.origin = CGPointMake(btn.origin.x, btn.origin.y - 20);
    } completion:^(BOOL finished) {
        [btn sendActionsForControlEvents:UIControlEventTouchUpInside];
        [self autoSmallDecisionsFxqActionAnimation:btn.tag + 1];
    }];
}

- (void)fxqAlertTaskMessageAction:(UIGestureRecognizer *)ges {
    UIButton *fxqBtn = (UIButton *)ges.view;
    NSInteger viewTag = fxqBtn.tag;
    [fxqBtn sendActionsForControlEvents:UIControlEventTouchUpInside];
    if (viewTag == 48) {
        [self showSmallDecisionsFxqResultWithTaskModel:nil viewTag:48];
    } else {
        if((viewTag - 1) <= self.fxqTaskList.count) {
            SmallDecisionsFxqTaskModel *model = self.fxqTaskList[viewTag - 1];
            [self showSmallDecisionsFxqResultWithTaskModel:model viewTag:viewTag];
        }
    }
}

- (void)showSmallDecisionsFxqResultWithTaskModel:(SmallDecisionsFxqTaskModel *)model
                                         viewTag:(NSInteger)tag {
    SmallDecisionsFxqResultViewController *fxqResultVC =[[SmallDecisionsFxqResultViewController alloc] init];
    if (tag >= 48) {
        fxqResultVC.title = @"抵达终点";
        fxqResultVC.resultMsg = @"胜利了✌🏻，可要求对方做你任何让你舒服的事情";
    } else {
        if (model.taskIcon) {
            fxqResultVC.title = model.taskTitle;
            fxqResultVC.resultMsg = model.taskContent;
            fxqResultVC.resultImageName = model.taskIcon;
        } else {
            fxqResultVC.title = model.taskTitle;
            fxqResultVC.resultMsg = model.taskContent;
        }
    }
    [SmallDecisionsNavigatorManager presentViewController:fxqResultVC showNavigationBar:NO animationType:SmallDecisionsAnimationTypeAlert];
}

- (void)setFxqTaskType:(SmallDecisionsFxqTaskType)fxqTaskType {
    _fxqTaskType = fxqTaskType;
    switch (fxqTaskType) {
        case 1: {
            self.title = @"暧昧模式";
            self.fxqTaskList = [NSArray yy_modelArrayWithClass:[SmallDecisionsFxqTaskModel class] json:[SmallDecisionsFxqTaskData loadFxqTaskAiMeiRenWu]];
        } break;
        case 2: {
            self.title = @"热恋模式";
            self.fxqTaskList = [NSArray yy_modelArrayWithClass:[SmallDecisionsFxqTaskModel class] json:[SmallDecisionsFxqTaskData loadFxqTaskReLianRenWu]];
        } break;
        case 3: {
            self.title = @"火热模式";
            self.fxqTaskList = [NSArray yy_modelArrayWithClass:[SmallDecisionsFxqTaskModel class] json:[SmallDecisionsFxqTaskData loadFxqTaskHuoReRenWu]];
        } break;
        case 4: {
            self.title = @"混合模式";
            self.fxqTaskList = [NSArray yy_modelArrayWithClass:[SmallDecisionsFxqTaskModel class] json:[SmallDecisionsFxqTaskData loadFxqTaskHunHeRenWu]];
        } break;
        default:
            break;
    }
}

- (UIView *)setRightBarButton {
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 30, 30);
    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightBtn setTitle:@"重新开始" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = SmallDecisionsSetFontSize(14);
    [rightBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
    return rightBtn;
}

- (void)rightBarButtonAction:(UIView *)view {
    [self loadSmallDecisionsFxqGame];
}

- (void)backBarButtonAction:(UIView *)view {
    [SmallDecisionsAlertViewController showAlertWithTitle:nil message:@"确定退出该游戏吗？" cancelText:@"取消" otherText:@"确定" dismissCompletion:^(SMALL_DECISIONS_PROJECT_ALERT_HANDLE_EVENTS event) {
        if(event == SMALL_DECISIONS_PROJECT_ALERT_HANDLE_EVENTS_OTHER) {
            [SmallDecisionsNavigatorManager popViewControllerAnimated:YES];
        }
    }];
}

@end
